package db

import (
	"MembershipRegist/models"
	"fmt"
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"net/url"
	"os"
	"time"
)

var DB *gorm.DB

func init() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&loc=%s&parseTime=true",
		beego.AppConfig.String("db_user"),
		beego.AppConfig.String("db_pass"),
		beego.AppConfig.String("db_host"),
		beego.AppConfig.String("db_port"),
		beego.AppConfig.String("db_name"),
		url.QueryEscape("Asia/Shanghai"),
	)

	var err error
	DB, err = gorm.Open("mysql", dsn)
	if err != nil {
		fmt.Println("数据库连接错误:", err)
		os.Exit(0)
	}

	DB.SingularTable(true)
	DB.DB().SetMaxOpenConns(100)
	DB.DB().SetMaxIdleConns(20)
	DB.DB().SetConnMaxLifetime(time.Minute)

	if beego.AppConfig.String("runmode") == "dev" {
		DB = DB.Debug()
	}

	DB.Debug().Set("gorm:table_options", "ENGINE=InnoDB").
		AutoMigrate(
			&models.Admin{},
			&models.OrganizationAdmin{},
			&models.Organization{},
			&models.OrganizationActivity{},
			&models.OrganizationActivityComment{},
			&models.OrganizationUser{},
			&models.OrganizationUserActivity{},
			&models.User{},
		)

	fmt.Println("数据库连接成功.")
}
